package com.shanxi.cz.module.biz.framework.mqtt.config;

import lombok.extern.slf4j.Slf4j;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.config.EnableIntegration;
import org.springframework.integration.mqtt.core.DefaultMqttPahoClientFactory;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;

@Slf4j
@EnableIntegration
@Configuration
public class MqttConfig {

    @Value("${mqtt.broker-url}")
    private String brokerUrl;

    @Value("${mqtt.username}")
    private String username;

    @Value("${mqtt.password}")
    private String password;

    @Bean
    public MqttConnectOptions mqttConnectOptions() {
        MqttConnectOptions options = new MqttConnectOptions();

        options.setServerURIs(new String[]{brokerUrl});
        if (username != null && !username.isEmpty()) {
            options.setUserName(username);
            log.info("使用用户名连接: {}", username);
        }
        if (password != null && !password.isEmpty()) {
            options.setPassword(password.toCharArray());
            log.info("使用密码连接");
        }
        options.setCleanSession(true);
        options.setAutomaticReconnect(true);
        options.setConnectionTimeout(30);
        options.setKeepAliveInterval(120);
        options.setMaxInflight(1000);

        // 重要：设置Will消息，用于检测连接状态
        options.setWill("client/status", "offline".getBytes(), 1, true);

        // 优化网络设置
        options.setExecutorServiceTimeout(30);

        log.info("MQTT连接配置完成 - Broker: {}", brokerUrl);
        log.info("- Broker: {}", brokerUrl);
        log.info("- KeepAlive: {}秒", options.getKeepAliveInterval());
        log.info("- 自动重连: {}", options.isAutomaticReconnect());
        return options;
    }

    @Bean
    public MqttPahoClientFactory mqttClientFactory() {
        DefaultMqttPahoClientFactory factory = new DefaultMqttPahoClientFactory();
        factory.setConnectionOptions(mqttConnectOptions());
        return factory;
    }
}